package controller

import (
	"log"

	"net/http"
	"phoenix/gin_web/dao"
	"phoenix/gin_web/model"
	"phoenix/gin_web/common"
	"phoenix/gin_web/utils"
	"phoenix/gin_web/dto"
	"phoenix/gin_web/response"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func Register(ctx *gin.Context) {
	name := ctx.PostForm("name")
	tel := ctx.PostForm("telephone")
	pwd := ctx.PostForm("password")

	if len(tel) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		return
	}

	if len(pwd) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return 
	}

	if len(name) < 1 {
		name = utils.RandString(10)
	}

	userDao := dao.GetUserDaoInstance()

	//查询数据库检查是否已有相同的用户
	if _, exist := userDao.IsTelephoneExist(&model.User{
		Telephone: tel,
	}); exist {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "不能重复注册一个电话号码")
		return
	} 

	//创建用户
	hasedPwd, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost )
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "加密错误")
		return
	}

	user := &model.User{
		Telephone: tel,
		Password: string(hasedPwd),
		Name: name,
	}

    err = userDao.CreateNewUser(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "创建用户失败")
		return
	}

	log.Printf("register user name=%s tel=%s", name, tel)
	response.Success(ctx, nil, "注册成功")
}

func Login(ctx *gin.Context) {
	//获取参数
	tel := ctx.PostForm("telephone")
	pwd := ctx.PostForm("password")

	if len(tel) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		return
	}

	if len(pwd) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}

	//数据验证
	userDao := dao.GetUserDaoInstance()

	//查找对应的user
	user, exist := userDao.IsTelephoneExist(&model.User{
		Telephone: tel,
	})
	if !exist {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	
	//判断密码是否正确
	if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pwd)) != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "密码不能少于6位")
		return
	}

	//发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "获取token失败")
		log.Printf("token generate error: %v", err)
		return
	}

	//返回结果
	response.Success(ctx, gin.H{
		"token": token,
	}, "登录成功")
}

func Info(ctx *gin.Context) {
	i, _ := ctx.Get("user")
	user, _ := i.(*model.User)
	
	response.Success(ctx, gin.H{
		"user": dto.ToUserDao(user),
	}, "")
	
}